//
//  AppDelegate.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/9.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "AppDelegate.h"
#import "baseAnalysis.h"
#import "CCLocationManager.h"
#import "getCommonDataMode.h"
@interface AppDelegate ()<UIAlertViewDelegate>{
    NSString *linkUrl;
}

@end

@implementation AppDelegate
@synthesize custom;
-(void)getAddress
{
    [[CCLocationManager shareLocation]getAddress:^(NSString *addressBlock) {
        NSLog(@"当前地址%@",addressBlock);
        
    }];
}
/**
 *  检测新版本
 *
 *  @param 接口   /release/sync
 *  @param 参数  head，body
 *
 *  @return 当前最新版本，是否升级，升级地址
 */
-(void)syncViersion{
    TIME
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"certificate"]==nil) {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"certificate"];
    }
    HEADDIC(nowTime, SYNCVERSION);
    NSDictionary *body = @{@"client_model":[appStatus shareAppStatus].client_model,
                           @"client_os":[appStatus shareAppStatus].client_os,
                           @"client_os_version":[appStatus shareAppStatus].client_os_version,
                           @"client_latitude":[appStatus shareAppStatus].client_latitude,
                           @"client_longitude":[appStatus shareAppStatus].client_longitude,
                           @"client_device":[appStatus shareAppStatus].client_device,
                           @"app_version":APP_VERSION,
                           };
    requestManage *request = [[requestManage alloc]init];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSLog(@"result___%@",result);
    NSMutableDictionary *json = [result objectFromJSONString];
    if ([[json objectForKey:@"err_code"] integerValue]==0) {
        NSMutableDictionary *data = [json objectForKey:@"data"];
        NSString *last_version = [data objectForKey:@"latest_version"];
        NSString *version = APP_VERSION;
        NSMutableArray * array=[NSMutableArray arrayWithArray:[last_version componentsSeparatedByString:@"."]];
        NSMutableArray * array1=[NSMutableArray arrayWithArray:[version componentsSeparatedByString:@"."]];
        if (![array isEqualToArray:array1]) {
            NSString *newVersion = [NSString stringWithFormat:@"%@ -> %@\n\n%@",version,last_version,last_version];
            if ([[data objectForKey:@"force_upgrade"] intValue] != 0) {
                linkUrl = [data objectForKey:@"download_url"];
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:newVersion delegate:self cancelButtonTitle:nil otherButtonTitles:@"立即更新", nil];
                alert.tag = 256;
                [alert show];
            }else{
                linkUrl = [data objectForKey:@"download_url"];
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"发现新版本" message:newVersion delegate:self cancelButtonTitle:@"稍后提醒" otherButtonTitles:@"立即更新", nil];
                alert.tag = 255;
                [alert show];
            }
        }
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 255) {
        if (buttonIndex == 0) {
            return;
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:linkUrl]];
//        exit(0);
    }else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:linkUrl]];
        exit(0);
    }
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 监控网络状态
    [MHAsiNetworkHandler startMonitoring];
    NSLog(@"Document___%@",DOCUMENTS);
    [self syncViersion];
    /**
     *  判断，用户登录返回的验证码
     */
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"certificate"]== nil) {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"certificate"];
    }
    [[NSUserDefaults standardUserDefaults] setObject:@"18210222179" forKey:@"tel"];
    [[NSUserDefaults standardUserDefaults] setObject:@"wangjilei" forKey:@"pwd"];
    TIME
    HEADDIC(nowTime, GETCOMMONDATA);
    NSDictionary *body = [NSDictionary dictionary];
    requestManage *request = [[requestManage alloc]init];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:body forKey:@"body"];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    NSMutableDictionary *json = [result objectFromJSONString];
    NSMutableDictionary *data = [json objectForKey:@"data"];
    [appStatus shareAppStatus].hot_keywords = [data objectForKey:@"hot_keywords"];
    [appStatus shareAppStatus].business = [data objectForKey:@"business"];
    [appStatus shareAppStatus].weixin_pic = [data objectForKey:@"weixin_pic"];
    /**
     *  公共信息接口，把公共信息保存到本地文件
     */
    if (result != nil) {
        NSError *error;
        NSString *filePath= FILE(@"getcommondata.txt");
        //需要写入的字符串
        //写入文件
        if ([result writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
            NSLog(@"写入成功");
        }else{
            NSLog(@"写入失败");
        }
    }
    
    RootViewController *root = [[RootViewController alloc]init];
    self.rootVC = root;
    [self getAddress];
    [appStatus shareAppStatus].tabBarController.delegate = self;
    self.window.rootViewController=[appStatus shareAppStatus].tabBarController;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
    [self performSelectorOnMainThread:@selector(updateCity:) withObject:path waitUntilDone:YES];
    return YES;
}
-(void)updateCity:(NSString *)path{
    [[appStatus shareAppStatus].provinceArray removeAllObjects];
    [[appStatus shareAppStatus].cityArray removeAllObjects];
    NSData *jsonData = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:nil];
    NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    for (int i = 0; i < [arr count]; i++) {
        NSMutableDictionary *province1 = [arr objectAtIndex:i];
        if ([[province1 objectForKey:@"level"] isEqualToString:@"1"]) {
            [[appStatus shareAppStatus].provinceArray addObject:province1];
        }else if ([[province1 objectForKey:@"level"] isEqualToString:@"2"]){
            [[appStatus shareAppStatus].cityArray addObject:province1];
        }
    }
}
-(void)switchRootViewController:(NSString *)rootController{
    [self getAddress];
    /**
     *  切换主页面窗口
     *  root -- 登录页面
     *  tabBarController -- 用户操作主页面
     */
    if ([rootController isEqualToString:@"root"]) {
        UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:self.rootVC];
        [nc setNavigationBarHidden:YES];
        nc.navigationBar.translucent = NO;
        self.window.rootViewController = nc;
    }else{
        self.window.rootViewController = [appStatus shareAppStatus].tabBarController;
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
